package com.eqxiu.ieditor.manager.controller;

import com.eqxiu.ieditor.weixin.api.MenuServiceApi;
import com.eqxiu.ieditor.weixin.api.WeixinMenuServiceApi;
import com.eqxiu.ieditor.weixin.dto.BottomMenuDTO;
import com.eqxiu.ieditor.weixin.dto.MenuReqDTO;
import com.eqxiu.weixin.api.WeiXinMPApi;
import com.google.common.collect.Maps;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/m/ie/menu")
public class MenuController {

	@Value("${weixin.button.appid}")
	private String MP_APPID;

	@Value("${weixin.button.url}")
	private String WEIXIN_MENU_URL;

	@Resource
	private WeiXinMPApi weiXinMPApi;

	private Logger logger = LoggerFactory.getLogger(getClass().getName());

    @Resource
	private MenuServiceApi menuServiceApi;

    @Resource
	private WeixinMenuServiceApi weixinMenuServiceApi;

	@PostMapping("/{page}")
	public String index(@PathVariable String page) {
		return "mp/" + page;
	}

	@PostMapping("/muti-list")
	@ResponseBody
	public Map<String, Object> findMutiMenuList(@RequestParam(value = "mpNameSearch", defaultValue = "1") Integer mpId,
											@RequestParam(value = "firstMenuSearch", defaultValue = "0") Long firstMenu,
											@RequestParam(value = "secondMenuSearch", defaultValue = "0") Long secondMenu,
											@RequestParam(value = "statusSearch", defaultValue = "0") Byte status) {
		logger.info("muti-list的入参为：mpId={}, firstMenu={}, secondMenu={}, status={}",
				mpId, firstMenu, secondMenu, status);
		List<MenuReqDTO> mutiMenuList = menuServiceApi.findMutiMenuList(mpId, firstMenu, secondMenu, status);
		int total = menuServiceApi.mutiMenuListCount(mpId, firstMenu, secondMenu, status);
		Map<String, Object> map = Maps.newHashMap();
		map.put("total", total);
		map.put("rows", mutiMenuList);
		return map;
	}

	@GetMapping("/list")
	@ResponseBody
	public List<BottomMenuDTO> findMenuList(@RequestParam(defaultValue = "0") Long upperId,
											@RequestParam(defaultValue = "1") Byte status) {
		logger.info("list接口的入参upperid为:{}，status为:{}", upperId, status);
		BottomMenuDTO bottomMenuDTO = new BottomMenuDTO();
		bottomMenuDTO.setUpperId(upperId).setStatus(status);
		List<BottomMenuDTO> menuList = menuServiceApi.findMenuList(bottomMenuDTO);
		logger.info("返回的列表为：{}", menuList);
		return menuList;
	}

	@GetMapping
	@ResponseBody
	public MenuReqDTO getMenu(@RequestParam Long id) {
		logger.info("getMenu的入参id为:{}", id);
        MenuReqDTO menuDTO = menuServiceApi.getMenu(id);
		logger.info("返回的menu为：{}", menuDTO);
		return menuDTO;
	}

	@PostMapping
	@ResponseBody
	public int save(@RequestBody MenuReqDTO menuReqDTO) {
		logger.info("save的入参为:{}", menuReqDTO);
		int save = menuServiceApi.save(menuReqDTO);
		this.push();
		return save;
	}

	@PostMapping(value = "/init")
	@ResponseBody
	public String init(@RequestBody Map<String, List> button) {
        logger.info("初始化数据：{}", button);
		List list = button.get("button");
		String s = new Gson().toJson(list);
		menuServiceApi.init(s);
		logger.info("开始把底部菜单推送到微信公众号!");
        return this.push();
	}

	@PutMapping
	@ResponseBody
	public int update(@RequestBody MenuReqDTO menuReqDTO) {
		logger.info("update的入参为:{}", menuReqDTO);
		int update = menuServiceApi.updateMenu(menuReqDTO);
		this.push();
		return update;
	}

	@PutMapping("/status")
	@ResponseBody
	public int updateStatus(@RequestBody BottomMenuDTO dto) {
		logger.info("update status的入参为:{}", dto);
		int i = menuServiceApi.updateByPrimaryKeySelective(dto);
		this.push();
		return i;
	}


	@GetMapping("/push")
	@ResponseBody
	public String push() {

	    logger.info("微信APPid为:{}", MP_APPID);
	    logger.info("更新微信底部菜单的链接为:{}", WEIXIN_MENU_URL);
		String weChatAccessToken = weiXinMPApi.getWeChatAccessToken(MP_APPID);
		logger.info("weChatAccessToken={}", weChatAccessToken);
		if (StringUtils.isBlank(weChatAccessToken)) {
		    logger.info("没有查询到token");
		    return "没有查询到token";
        }
		logger.info("获得的token为：{}", weChatAccessToken);
		RestTemplate restTemplate = new RestTemplate();
		String url = WEIXIN_MENU_URL + weChatAccessToken;
		logger.info("更新微信菜单的url为：{}", url);
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
		String s = weixinMenuServiceApi.findWeixinMenuList();
		logger.info("要发送给微信的为：{}", s);
		HttpEntity<String> request = new HttpEntity<>(s, headers);
		ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class);
		String body = response.getBody();
		logger.info("微信返回：{}", body);
		return body;
	}


	@GetMapping("/menu-list")
	@ResponseBody
	public String menuList() {
		String s = weixinMenuServiceApi.findWeixinMenuList();
		System.out.println("====================================");
		System.out.println(s);
		return s;
	}


}
